import { Plugin as HighlightWeekends } from 'gantt-schedule-timeline-calendar/dist/plugins/highlight-weekends.esm.min.js';
import { Plugin as TimelinePointer } from 'gantt-schedule-timeline-calendar/dist/plugins/timeline-pointer.esm.min.js';
import { Plugin as Selection } from 'gantt-schedule-timeline-calendar/dist/plugins/selection.esm.min.js';
import { Plugin as ItemResizing } from 'gantt-schedule-timeline-calendar/dist/plugins/item-resizing.esm.min.js';
import { Plugin as ItemMovement } from 'gantt-schedule-timeline-calendar/dist/plugins/item-movement.esm.min.js';
import {
  Plugin as TimeBookmarks,
  Bookmarks
} from 'gantt-schedule-timeline-calendar/dist/plugins/time-bookmarks.esm.min.js';
import { Plugin as CalendarScroll } from 'gantt-schedule-timeline-calendar/dist/plugins/calendar-scroll.esm.min.js';
import { Plugin as ProgressBar } from 'gantt-schedule-timeline-calendar/dist/plugins/progress-bar.esm.min.js';
import { Plugin as DependencyLines } from 'gantt-schedule-timeline-calendar/dist/plugins/dependency-lines.esm.min.js';
import { Plugin as ExportImage } from 'gantt-schedule-timeline-calendar/dist/plugins/export-image.esm.min.js';
import { Plugin as ExportPDF } from 'gantt-schedule-timeline-calendar/dist/plugins/export-pdf.esm.min.js';
import GSTC, { GSTCResult } from 'gantt-schedule-timeline-calendar';
import { useGanttStore } from '@/store/modules/ganttStore';
import dayjs from 'dayjs';
import type { BlogPost, PostDependency, PostMilestone, Topic } from '@/components/GanttChart/types';

const store = useGanttStore();
// 定义是否启用时间吸附功能
const snapTime = true;
// 时间吸附开始时间的函数
const snapStart = ({ startTime, vido }) => {
  if (!snapTime) return startTime;
  const date = vido.api.time.findOrCreateMainDateAtTime(startTime.valueOf());
  console.log('时间吸附-开始部分', date);
  return date.leftGlobalDate;
};

// 时间吸附结束时间的函数
const snapEnd = ({ endTime, vido }) => {
  if (!snapTime) return endTime;
  const date = vido.api.time.findOrCreateMainDateAtTime(endTime.valueOf());
  console.log('时间吸附-结束部分', date);
  return date.rightGlobalDate;
};

// 判断项目是否可以移动的函数
const canMove = item => {
  const row = store.gstc!.api.getRow(item.rowId);
  if (row.vacations) {
    for (const vacation of row.vacations) {
      const vacationStart = vacation.from;
      const vacationEnd = vacation.to;
      // item start time inside vacation
      if (item.time.start >= vacationStart && item.time.start <= vacationEnd) {
        return false;
      }
      // item end time inside vacation
      if (item.time.end >= vacationStart && item.time.end <= vacationEnd) {
        return false;
      }
      // vacation is between item start and end
      if (item.time.start <= vacationStart && item.time.end >= vacationEnd) {
        return false;
      }
      // item start and end time is inside vacation
      if (item.time.start >= vacationStart && item.time.end <= vacationEnd) {
        return false;
      }
    }
  }
  return true;
};

/**
 * @type {import('../../dist/plugins/item-resizing').Options}
 */
// 项目调整大小选项配置
const itemResizeOptions = {
  threshold: 25,
  snapToTime: {
    start: snapStart,
    end: snapEnd
  },
  events: {
    onResize({ items }) {
      for (const item of items.after) {
        if (!canMove(item)) return items.before;
      }
      return items.after;
    }
  }
};

/**
 * @type {import('../../dist/plugins/item-movement').Options}
 */
// 项目移动选项配置
const itemMovementOptions = {
  threshold: {
    horizontal: 25,
    vertical: 25
  },
  snapToTime: {
    start: snapStart,
    end({ endTime }) {
      return endTime;
    }
  },
  events: {
    onMove({ items }) {
      for (let i = 0, len = items.after.length; i < len; i++) {
        const item = items.after[i];
        if (!canMove(item)) return items.before;
      }
      return items.after;
    }
  }
};

const ITEM = 'chart-timeline-items-row-item';
/**
 * @type { import("gantt-schedule-timeline-calendar/dist/plugins/selection").Options }
 */
const selectionOptions = {
  events: {
    // onStart(lastSelected) {
    //   console.log("Selection starts", lastSelected);
    // },
    // onSelecting(selecting, last) {
    //   selecting[ITEM] = selecting[ITEM].filter((item) => {
    //     if (item.frozen) {
    //       console.log("Removing frozen item from selection", item);
    //       return false;
    //     }
    //     const itemStartDate = store.gstc!.api.time.date(item.time.start).format("YYYY-MM-DD");
    //     if (itemStartDate === "2021-09-22") {
    //       console.log("item ignored because of date", itemStartDate);
    //       return false;
    //     }
    //     const endsBeforeToday = item.time.end < store.gstc!.api.time.date().startOf("day").valueOf();
    //     if (endsBeforeToday) {
    //       return false;
    //     }
    //     return true;
    //   });
    //   console.log("selecting items", selecting[ITEM]);
    //   console.log("last selected item", last);
    //   return selecting;
    // },
    onEnd(selected) {
      selected[ITEM] = selected[ITEM].filter(item => {
        if (item.frozen) {
          console.log('Removing frozen item from selection', item);
          return false;
        }
        // const itemStartDate = store.gstc!.api.time.date(item.time.start).format("YYYY-MM-DD");
        // if (itemStartDate === "2021-09-22") {
        //   console.log("item ignored because of date", itemStartDate);
        //   return false;
        // }
        // const endsBeforeToday = item.time.end < store.gstc!.api.time.date().startOf("day").valueOf();
        // if (endsBeforeToday) {
        //   // 结束日为过去日的项目不允许选中
        //   console.log("item ignored because it ends before today", item);
        //   return false;
        // }
        return true;
      });
      store.setActivePosts(selected[ITEM].map(item => item.sourceId));
      // selected[ITEM].map(item => item.id);
      console.log('Selection ends', selected[ITEM]);
      return selected;
    }
  }
};
const bookmarksOptions = () => {
  // 生成书签数据
  const bookmarks: Bookmarks = store.milestones.reduce((acc, milestone: PostMilestone) => {
    acc[milestone.id] = {
      time: dayjs(milestone.date).toDate(),
      label: milestone.name,
      style: {
        background: store.getRandomColor()
      }
    };
    return acc;
  }, {});
  return bookmarks;
};

export function useGanttPlugins() {
  const loadPlugins = () => [
    HighlightWeekends(), // 高亮周末插件
    TimelinePointer(), // 时间线指针插件，必须在选择、调整大小和移动插件之前
    Selection(selectionOptions), // 选择插件
    ItemResizing(itemResizeOptions), // 调整大小插件，必须在移动插件之前
    ItemMovement(itemMovementOptions), // 移动插件
    CalendarScroll(), // 日历滚动插件
    ProgressBar(), // 进度条插件
    TimeBookmarks({
      // 时间书签插件
      bookmarks: bookmarksOptions()
    }),
    DependencyLines({
      // 依赖线插件
      onLine: [
        line => {
          line.type = GSTC.api.sourceID(line.fromItem.id) === '3' ? 'smooth' : 'square';
          return line;
        }
      ]
    }),
    ExportImage(), // 导出图片插件
    ExportPDF() // 导出PDF插件
  ];
  // console.log("plugins: ", loadPlugins());
  return { loadPlugins };
}
